package com.campus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.campus.dao.SysUserMapper;
import com.campus.entry.SysUser;
import com.campus.exception.BusinessException;
import com.campus.pojo.dto.AccountDto;
import com.campus.response.ResultCode;
import com.campus.service.AccountService;
import com.campus.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private JWTUtil jwtUtil;

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 登录
     * @param account
     * @return token
     */
    @Override
    public Map<String, String> login(AccountDto account) {
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper
                .select(SysUser::getId,SysUser::getLoginName,SysUser::getPassword)
                .eq(SysUser::getLoginName,account.getLoginName());
        SysUser sysUser = sysUserMapper.selectOne(lambdaQueryWrapper);
        if (Objects.isNull(sysUser)){
            throw new BusinessException(ResultCode.NO_REGISTER);
        }
        if (!sysUser.getPassword().equals(account.getPassword())){
            throw new BusinessException(ResultCode.ERROR_USERNAME_PASSWORD);
        }
        String jwts = jwtUtil.creatJWT(sysUser.getId());
        Map<String,String> map=new HashMap<>();
        map.put("token",jwts);

        return map;
    }
}
